<template>
  <a-modal v-model:open="open" :title="fromModel.menuId?'编辑':'新增'"
  cancel-text="取消"
           :confirm-loading="confirmLoading" @ok="handleOk" @cancel="close">
   <div>
     <a-form
         ref="formRef"
         :model="fromModel"
         :rules="rules"
        :label-col="{ span: 5 }"
     >
       <a-form-item label="菜单类型" name="type">

         <a-radio-group v-model:value="fromModel.type" :options="typeOption" />
       </a-form-item>
       <a-form-item label="上级菜单" name="parentId">
         <a-tree-select
             v-model:value="fromModel.parentId"
             style="width: 100%"
             :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
             placeholder="请选择上级菜单"
             allow-clear
             tree-default-expand-all
             :tree-data="menuTree"
             tree-node-filter-prop="label"
             :field-names="{
            children: 'children',
            label: 'name',
            value: 'menuId',
          }"
         >
         </a-tree-select>
       </a-form-item>
       <a-form-item :label="getLabelName()" name="name">
         <a-input v-model:value="fromModel.name" :placeholder="'请输入'+getLabelName()" allow-clear/>
       </a-form-item>
       <a-form-item label="菜单路径" name="path" v-if="fromModel.type===1">
         <a-input v-model:value="fromModel.path" placeholder="请输入菜单路径" allow-clear/>
       </a-form-item>
       <a-form-item label="授权标识" name="permission" v-if="fromModel.type!==0">
         <a-input v-model:value="fromModel.permission" placeholder="请输入授权标识,多个使用,分割" allow-clear/>
       </a-form-item>

       <a-form-item label="菜单图标" name="icon" v-if="fromModel.type!==2">

         <a-popover v-model:open="iconVisible"
                    title="请选择图标"
                    trigger="click"
                    placement="bottom"
         >
           <template #content>
            <div class="icon-group">
              <div class="icon-item" v-for="item in iconList" :key="item"
                   @click="selectIcon(item)"
                   :class="{
                     active:fromModel.icon===item
                   }"
              >
                <my-icon :name="item" width="25px" height="25px"/>
              </div>
            </div>
           </template>
           <a-input v-model:value="fromModel.icon" placeholder="请输入菜单图标" allow-clear/>
         </a-popover>
       </a-form-item>

       <a-form-item label="序号" name="sortOrder" v-if="fromModel.type!==2">
         <a-input-number :min="0" v-model:value="fromModel.sortOrder" placeholder="请输入序号" allow-clear/>
       </a-form-item>

     </a-form>
   </div>
  </a-modal>
</template>
<script setup lang="ts">
import {ref, defineProps, defineEmits, watch, defineComponent} from 'vue'
import {Menu} from "@/types/global.ts";
import myIcon from '@/components/my-icon/index.vue'
import {saveMenu,editMenu,menuSelectTree} from "@/api/sys-setting/menu.ts";
import {useSystemStore} from '@/stroe'
import { useRouter} from "vue-router";
defineComponent({
  myIcon
})
  const props = defineProps(['menu','modelValue']);
const systemStore =useSystemStore();
const router = useRouter();
  const emits = defineEmits(['update:modelValue','success']);
  const generateMenu = ():Menu=>{
    return{
      name:'',
      permission: '',
      path: '',
      parentId:  -1,
      parentName: null,
      icon:'',
      sortOrder:  0,
      type:0,

    }
  }
  const typeOption = [
    { label: '目录', value: 0 },
    { label: '菜单', value: 1 },
    { label: '按钮', value: 2 }
  ]
  const fromModel = ref(generateMenu());
  const open = ref(false)
  const confirmLoading = ref(false);
  const formRef = ref();
  const iconList = ref([]);
  //@ts-ignore
  const svgStr =window._iconfont_svg_string_4684822;
  const menuTree = ref([])
  const iconVisible = ref(false)
const rules = {
  type:[
    { required: true, message: '请选择菜单类型'}
  ],
  parentId:[
    { required: true, message: '上级菜单不能为空'}
  ],
  name:[
    { required: true, message: '菜单名称不能为空'}
  ],
  path:[
    { required: true, message: '菜单名称不能为空'}
  ],
  permission:[
    { required: true, message: '授权标识不能为空'}
  ]
}
const close = ()=>{
  fromModel.value = generateMenu();
  emits('update:modelValue',false)
}
  const getLabelName = ()=>{
      const arr = ['目录','菜单','按钮'];
      return arr[fromModel.value.type as number]+"名称"
  }
  const handleOk = ()=>{
    formRef.value
        .validate()
        .then(async () => {
          confirmLoading.value = true;
          if (fromModel.value.menuId){
           await editMenu(fromModel.value);

          }else {
            await saveMenu(fromModel.value)
          }

          confirmLoading.value = false;
          emits('success')
          systemStore.refreshMenu(router);
        })
        .catch(error => {
          console.log('error', error);
        })
  }
  const selectIcon = (name:string)=>{
    fromModel.value.icon = name;
    iconVisible.value = false
  }
  function extractIds(str) {
    // 正则表达式匹配以"id="开头，后面跟着任意字符，直到遇到引号为止
    const  ids = str.match(/id=["'](.*?)["']/g);
    return ids ? ids.map(function(id) { return id.replace(/id=["']/,'').replace(/["']/,''); }) : [];
  }
  const getSelectMenu = ()=>{
    menuSelectTree().then((res:any)=>{
      menuTree.value = res.result
    })
  }
  watch(()=>props.menu,(value)=>{
    fromModel.value = value;
   if(svgStr){
     const iconNames = extractIds(svgStr);
     iconList.value = iconNames.map((item:string)=>item.replace('icon-',''))
   }
  },{immediate:true,deep:true})
watch(()=>props.modelValue,(value)=>{
  open.value = value;
  if(value){
    getSelectMenu();
  }
},{immediate:true})
</script>
<style scoped lang="scss">
.icon-group{
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  max-height: 300px;
  overflow: auto;
  .icon-item{
    margin: 5px;
    border:1px solid #949090;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor:pointer;
    border-radius: 5px;
    &.active{
      border:2px solid #0cacd3;
    }
  }
}
.icon-svg {
  vertical-align: -0.15em;
  fill: #131415;
  overflow: hidden;
}
</style>
